<template>
  <view class="page-container">
    <u-navbar :is-back="true" title="练习报告"></u-navbar>
    <view v-if="dttype === 1" class="container">
      <!-- 圆角方框01 -->
      <view class="box box01">
        <view class="charts-box">
          <qiun-data-charts type="arcbar" :opts="opts" :chartData="chartData" />
        </view>

        <!-- 分割线 -->
        <view class="divider"></view>

        <view class="data-info">
          <view class="data-row">
            <span class="data-title">练习类型:</span>
            <span class="data-value">{{ reportData.exerciseType }}</span>
          </view>
          <view class="data-row">
            <span class="data-title">交卷时间:</span>
            <span class="data-value">{{ formattedSubmissionTime }}</span>
          </view>
          <view class="data-row">
            <span class="data-title">答题时间:</span>
            <span class="data-value">{{ formatTime(reportData.timeTaken) }}</span>
          </view>
          <view class="data-row">
            <span class="data-title">正确率:</span>
            <span class="data-value">{{ reportData.accuracy }}%</span>
          </view>
        </view>
      </view>

      <!-- 圆角方框02 -->
      <view class="box box02">
        <view class="header">
          <view class="header-left">
            <image class="header-icon" src="https://xyh.zjit.ac.cn/profile/upload/2024/12/06/报告答题卡.png" mode="aspectFit" />
            <text class="header-text">答题卡</text>
          </view>
          <view class="status-indicators">
            <view class="status-item">
              <view class="dot" style="background-color: #CD2626;"></view>
              <text>错误</text>
            </view>
            <view class="status-item">
              <view class="dot" style="background-color: #09AFFF;"></view>
              <text>正确</text>
            </view>
          </view>
        </view>

        <view style="padding: 5px;width: 100%;display: flex;flex-wrap: wrap;justify-content: left">
          <button v-for="(answer, index) in answers" :key="index" :style="{
              backgroundColor: answer.userAnswer === null 
                ? '#CD2626' 
                : (answer.userAnswer === answer.answer ? '#09AFFF' : '#FF0000')
            }" class="circle-button">
            <text class="circle-button-text">{{ index + 1 }}</text>
          </button>
        </view>
      </view>

      <!-- 查看解析按钮 -->
      <view class="button-container">
        <button @click="viewAnalysis">查看解析</button>
      </view>
    </view>

    <view v-if="dttype === 2" class="container02" @touchstart="touchStart" @touchend="touchEnd">
      <view class="content-area">
        <u-tabs-swiper ref="tabsSwiper" :list="currentTab === '材料' ? materialsList : questionsList" bg-color="#fcfcfc" 
                        :current="currentMaterialIndex" @change="onTabChange" :is-scroll="false" 
                        active-color="#2979ff" inactive-color="#606266" font-size="30" bar-height="6" bar-width="40"></u-tabs-swiper>
        <div v-if="currentTab === '材料'">
          <u-parse :html="currentMaterials[currentMaterialIndex]" style="font-size: 13px;" 
                   :selectable="true" :lazy-load="true"></u-parse>
        </div>
        <div v-if="currentTab === '问题'">
          <u-parse :html="currentContent[currentMaterialIndex]" style="font-size: 13px;" 
                   :selectable="true" :lazy-load="true"></u-parse>
        </div>
      </view>

      <view v-if="currentTab === '问题'">
        <view class="content-area">
          <div class="data-row">
            <strong class="data-title">我的作答:</strong>
          </div>
          <div class="data-row">
            <u-parse :html="currentUserAnswer[currentMaterialIndex]" style="font-size: 15px;"></u-parse>
          </div>
          <view class="divider"></view>
          <view class="data-row">
            <span class="data-title"><strong>成绩:</strong></span>
            <span class="data-Grade">{{ currentGrade[currentMaterialIndex] }}</span>
          </view>
        </view>

        <view class="content-area" v-if="currentTeacherAnswer[currentMaterialIndex]">
          <div class="data-row">
            <span class="data-title"><strong>教师点评:</strong></span>
          </div>
          <div class="data-row">
            <u-parse :html="currentTeacherAnswer[currentMaterialIndex]" style="font-size: 15px;"></u-parse>
          </div>
        </view>

        <div class="content-area">
          <div class="data-row">
            <span class="data-title"><strong>参考答案:</strong></span>
          </div>
          <div class="data-row">
            <u-parse :html="currentSuggestedAnswers[currentMaterialIndex]" style="font-size: 15px;"></u-parse>
          </div>
        </div>
      </view>

      <view class="space"></view>

      <view style="position: fixed; bottom: 0px; width: 750rpx; display: flex; flex-direction: column; border-top: 1px solid #ccc; padding-top: 5px; padding-bottom: 5px; background-color: white; z-index: 1019;">
        <div class="tabs-and-input-row" style="display: flex; align-items: center; justify-content: center; width: 100%;">
          <div class="tabs-container">
            <div class="tab" :class="{ active: currentTab === '材料' }" @click="selectTab('材料')">材料</div>
            <div class="tab" :class="{ active: currentTab === '问题' }" @click="selectTab('问题')">问题</div>
          </div>
        </div>
      </view>
    </view>
  </view>
</template>

<script>
import { getSlpaper } from '@/api/business/slpaper'; // 导入获取试卷的 API
import { getSlquestion } from '@/api/business/slquestion'; // 导入获取问题的 API

export default {
  data() {
    return {
      dttype: null,
      currentTab: '材料',
      currentMaterialIndex: 0,
      currentMaterials: [],
      currentContent: [],
      currentSuggestedAnswers: [],
      currentGrade: [],
      currentUserAnswer: [],
      currentTeacherAnswer: [],
      materialsList: [],
      questionsList: [],
      chartData: {},
      startX: 0,
      opts: {
        title: {
          name: "答对",
          fontSize: 18,
          color: "#666666"
        },
        subtitle: {
          name: "0",
          fontSize: 25,
          color: "#000000"
        },
        extra: {
          arcbar: {
            type: "default",
            width: 9
          }
        }
      },
      answers: [],
      isSubmitted: true,
      reportData: {
        exerciseType: '',
        submissionTime: '',
        time: '',
        timeTaken: 0,
        accuracy: 0,
        totalQuestions: [],
        incorrectQuestions: [],
        user_id: null,
        paper_id: null,
        question_id: null,
        user_answers: [],
        status: '',
        grade: [],
        teacher_answers: [],
        suggested_answers: []
      }
    };
  },
  onLoad(options) {
    // 获取 dttype 参数
    if (options.dttype) {
      this.dttype = parseInt(options.dttype); // 将 dttype 转换为数字
    }

    if (options.slreport) {
      this.reportData = JSON.parse(decodeURIComponent(options.slreport));
      this.fetchData();
    }

    if (options.data) {
      this.reportData = JSON.parse(decodeURIComponent(options.data));
      this.updateSubtitle();
      this.initializeAnswers();
      this.updateChartData();
      this.fetchData();
    }
  },
  computed: {
    formattedSubmissionTime() {
      if (!this.reportData.time) {
        const rawTime = this.reportData.submissionTime;
        const regex = /(\d{4})\/(\d{1,2})\/(\d{1,2})(上午|下午)?(\d{1,2}):(\d{2}):(\d{2})/;
        const match = rawTime.match(regex);
        if (match) {
          const year = match[1];
          const month = match[2];
          const day = match[3];
          const period = match[4];
          let hour = parseInt(match[5]);
          const minute = match[6];
          const second = match[7];

          if (period === '下午' && hour < 12) {
            hour += 12;
          } else if (period === '上午' && hour === 12) {
            hour = 0;
          }
          return `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
        }
        return rawTime;
      }
    }
  },
  methods: {
    updateSubtitle() {
      const totalQuestions = this.reportData.totalQuestions || [];
      const incorrectQuestions = this.reportData.incorrectQuestions || [];
      const correctCount = totalQuestions.length - incorrectQuestions.length;
      this.opts.subtitle.name = correctCount.toString();
    },
    initializeAnswers() {
      this.answers = this.reportData.totalQuestions.map((questionId) => {
        return {
          questionId: questionId,
          userAnswer: this.reportData.incorrectQuestions.includes(questionId) ? null : questionId.userAnswer,
          answer: questionId.answer
        };
      });
    },
    updateChartData() {
      const correctCount = this.reportData.totalQuestions.length - this.reportData.incorrectQuestions.length;
      const totalCount = this.reportData.totalQuestions.length;
      const correctRate = totalCount ? (correctCount / totalCount) * 100 : 0;
      this.chartData = {
        series: [
          {
            name: "正确率",
            color: "#2fc25b",
            data: correctRate / 100
          }
        ]
      };
    },
    viewAnalysis() {
      uni.navigateBack({
        delta: 1
      });
    },
    formatTime(seconds) {
      if (seconds < 60) {
        return `${seconds}秒`;
      } else if (seconds < 3600) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes}分${remainingSeconds}秒`;
      } else {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const remainingSeconds = seconds % 60;
        return `${hours}小时${minutes}分${remainingSeconds}秒`;
      }
    },
    fetchData() {
      const { paper_id, question_id } = this.reportData;
      // 根据 paper_id 获取试卷数据
      if (paper_id) {
        getSlpaper(paper_id).then(response => {
          if (response && response.code === 200) {
            // 确保 materials 和 content 是数组
            this.currentPaper = response.data;
            this.currentMaterials = JSON.parse(this.currentPaper.materials || '[]');
            this.currentContent = JSON.parse(this.currentPaper.content || '[]');
            this.currentSuggestedAnswers = JSON.parse(this.currentPaper.suggestedAnswer || '[]');

            this.currentNmmsl = this.reportData;
            this.currentGrade = JSON.parse(this.currentNmmsl.grade || '[]');
            this.currentUserAnswer = JSON.parse(this.currentNmmsl.user_answers || '[]');
            this.currentTeacherAnswer = JSON.parse(this.currentNmmsl.teacher_answers || '[]');
            
            // 初始化 tabs
            this.materialsList = this.currentMaterials.map((_, index) => ({
              name: `材料${this.toChineseNumber(index + 1)}`
            }));
            this.questionsList = this.currentContent.map((_, index) => ({
              name: `问题${this.toChineseNumber(index + 1)}`
            }));
          } else {
            console.error('获取试卷数据失败:', response.msg || '未知错误');
          }
        }).catch(error => {
          console.error('获取试卷数据时出错:', error);
        });
      }

      // 根据 question_id 获取问题数据
      if (question_id) {
        getSlquestion(question_id).then(response => {
          if (response && response.code === 200) {
            // 确保 materials 和 content 是数组
            this.currentQuestion = response.data;
            this.currentMaterials = JSON.parse(this.currentQuestion.materials || '[]');
            this.currentContent = JSON.parse(this.currentQuestion.content || '[]');
            this.currentSuggestedAnswers = JSON.parse(this.currentQuestion.suggestedAnswer || '[]');

            this.currentNmsl = this.reportData;
            this.currentGrade = JSON.parse(this.currentNmsl.grade || '[]');
            this.currentUserAnswer = JSON.parse(this.currentNmsl.user_answers || '[]');
            this.currentTeacherAnswer = JSON.parse(this.currentNmsl.teacher_answers || '[]');
            // 初始化 tabs
            this.materialsList = this.currentMaterials.map((material, index) => ({
              name: `材料${this.toChineseNumber(index + 1)}`
            }));
            this.questionsList = this.currentContent.map((content, index) => ({
              name: `问题${this.toChineseNumber(index + 1)}`
            }));
          } else {
            console.error('获取问题数据失败:', response.msg || '未知错误');
          }
        }).catch(error => {
          console.error('获取问题数据时出错:', error);
        });
      }
    },
    selectTab(tab) {
      this.currentTab = tab;
      this.currentMaterialIndex = 0;
    },
    onTabChange(index) {
      this.currentMaterialIndex = index;
    },
    toChineseNumber(num) {
      const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
      return chineseNumbers[num] || '';
    },
    touchStart(event) {
      this.startX = event.touches[0].clientX; // 记录触摸开始的X坐标
    },
    touchEnd(event) {
      const endX = event.changedTouches[0].clientX; // 触摸结束的X坐标
      const distance = this.startX - endX; // 计算滑动的距离
      if (distance > 50) {
        // 向左滑动，进入下一tab
        this.selectNextTab();
      } else if (distance < -50) {
        // 向右滑动，返回上一tab
        this.selectPreviousTab();
      }
    },
    selectNextTab() {
      if (this.currentTab === '材料' && this.currentMaterialIndex < this.currentMaterials.length - 1) {
        this.currentMaterialIndex++;
      } else if (this.currentTab === '问题' && this.currentMaterialIndex < this.currentContent.length - 1) {
        this.currentMaterialIndex++;
      }
    },
    selectPreviousTab() {
      if (this.currentTab === '材料' && this.currentMaterialIndex > 0) {
        this.currentMaterialIndex--;
      } else if (this.currentTab === '问题' && this.currentMaterialIndex > 0) {
        this.currentMaterialIndex--;
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.data-title {
  font-weight: bold;
  font-size: 18px;
  color: #000000;
}

.data-Grade {  font-weight: bold;
  font-size: 18px;
  color: #EE2C2C;
}

.data-value {
  font-size: 15px;
  color: #2e2928;
}

.space {
  padding-bottom: 15%;
}
.content-area {
  padding: 10px;
  background-color: #fcfcfc;
  border: 1px solid #ccc;
  border-radius: 10px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tabs-container {
  display: flex;
  background-color: #e0f7fa;
  border-radius: 20px;
  overflow: hidden;
  width: 180rpx;
  margin-right: 20rpx;
  height: 60rpx;
  justify-content: center;
}

.tab {
  flex: 1;
  padding: 5px;
  text-align: center;
  color: black;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

.tab.active {
  background-color: #1976d2;
  color: white;
}

.page-container {
  display: flex;           /* 使用 Flexbox 布局 */
  flex-direction: column;  /* 垂直排列子元素 */
  height: 100vh;          /* 设置页面容器高度为 100% 视口高度 */
}

.container {
  padding: 16px;
  background-color: #f4f7fe; /* 设置背景颜色为 #f4f7fe */
  flex: 1;                    /* 允许容器扩展以填充可用空间 */
  display: flex;              /* 使用 Flexbox 布局 */
  flex-direction: column;     /* 垂直排列子元素 */
}

.box {
  border-radius: 10px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #ffffff;
}

.box01 {
  margin-bottom: 16px; /* 为了让两个方框之间有间距 */
}

.charts-box {
  width: 90%;  /* 修改为你想要的宽度 */
  height: 150px; /* 修改为你想要的高度 */
  margin: 0 auto; /* 居中显示 */
}

.divider {
  height: 1px;               /* 设置分割线的高度 */
  background-color: #ccc;    /* 设置分割线的颜色 */
  margin: 5px 0;            /* 上下间距 */
}

.data-info {
  margin-top: 16px;
}

.data-row {
  display: flex;           /* 使用 Flexbox 布局 */
  justify-content: space-between; /* 左右两侧对齐 */
  margin: 8px 0;          /* 上下间距 */
  color: #666666;         /* 设置文字颜色为灰色 */
}

.button-container {
  text-align: center;
  margin-top: auto; /* 将按钮推到页面底部 */
  margin-bottom: 16px; /* 为按钮底部添加一些间距 */
}

.circle-button {
  border-radius: 50%;
  width: 50px; /* 设置宽度 */
  height: 50px; /* 设置高度 */
  margin: 5px;
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  font-size: 16px; /* 设置字体大小 */
  color: white; /* 字体颜色 */
}

/* 新增样式 */
.header {
  display: flex; 
  justify-content: space-between; /* 使左右两部分分开 */
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 5px; /* 为 header 添加下间距 */
}

.header-left {
  display: flex; /* 使用 Flexbox 布局 */
  align-items: center; /* 垂直居中对齐 */
}

.header-icon {
  width: 40px; /* 设置图标宽度 */
  height: 40px; /* 设置图标高度 */
  margin-right: 2px; /* 图标与文字之间的间距，减少间距 */
}

.header-text {
  font-size: 20px; /* 设置文字大小 */
  font-weight: bold; /* 加粗文字 */
}

.status-indicators {
  display: flex; 
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-end; /* 右对齐 */
  margin-left: auto; /* 将状态指示器推向右侧 */
}

.status-item {
  display: flex; 
  align-items: center; /* 垂直居中对齐 */
  margin-left: 16px; /* 状态项之间的间距 */
}

.dot {
  width: 10px; /* 圆点宽度 */
  height: 10px; /* 圆点高度 */
  border-radius: 50%; /* 圆形 */
  margin-right: 4px; /* 圆点与文字之间的间距 */
}
</style>
